package com.banciyuan.bcywebview.biz.event;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.EventApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Event;

/**
 * Created by squall on 2015/9/28.
 */
public class EventListActivity extends BaseActivity {

    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private RequestQueue mQueue;
    private int page = 1;
    private boolean end_flag = false;
    private boolean load_flag = false;
    private EventListAdapter eventListAdapter;
    private List<Event> elist = new ArrayList<Event>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_list);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.discoverevent));
    }

    @Override
    protected void initUi() {
        mRefreshLv = (PullToRefreshListView) findViewById(R.id.topic_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!load_flag) {
                    load_flag = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }

            }
        });

        mRefreshLv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!load_flag) {
                    if (!end_flag) {
                        page++;
                        initData();
                    }
                }
            }
        });

        mContentLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int index = i - 1;
                if (index < 0 || index > elist.size()) return;
                gotoUtil.gotoAct(EventListActivity.this, EventDetailActivity.class, elist.get(index).getEvent_id());
            }
        });
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + EventApi.getListall();
        List<BcyPair> BcyPairList = new ArrayList<BcyPair>();
        BcyPairList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map<String, String> map = HttpUtils.getData(BcyPairList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EventListActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");

                        Gson gson = new Gson();
                        List<Event> templist = gson.fromJson(jsonArray.toString(), new TypeToken<List<Event>>() {
                        }.getType());
                        if (!templist.isEmpty()) {
                            dealJson(templist);
                        } else {
                            if (page == 1) {
                                mProgressbarHelper.onNodata();
                                mRefreshLv.onRefreshComplete();
                                load_flag = false;
                            } else {
                                mProgressbarHelper.onSuccess();
                                mRefreshLv.onRefreshComplete();
                                load_flag = false;
                            }
                            end_flag = true;
                        }

                    } catch (Exception e) {
                        mProgressbarHelper.onFailed();
                        mRefreshLv.onRefreshComplete();
                        load_flag = false;
                    }
                } else {
                    mProgressbarHelper.onFailed();
                    mRefreshLv.onRefreshComplete();
                    load_flag = false;
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                mRefreshLv.onRefreshComplete();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, EventListActivity.this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);

    }

    private void dealJson(List<Event> templist) {
        if (page == 1) {
            elist.clear();
        }
        elist.addAll(templist);
        if (eventListAdapter == null) {
            eventListAdapter = new EventListAdapter(EventListActivity.this, elist);
            mContentLv.setAdapter(eventListAdapter);
        } else {
            eventListAdapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
        mRefreshLv.onRefreshComplete();
        load_flag = false;
    }
}
